"""
预约相关 API
"""
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import Optional
from datetime import datetime
from app.core.database import get_db
from app.core.dependencies import get_current_user
from app.schemas.booking import (
    BookingResponse, BookingCreate, OrderFilter
)
from app.schemas.common import ApiResponse, PageData
from app.models.booking import Booking, BookingParticipant
from app.models.user import User
from app.utils.helpers import generate_id

router = APIRouter()


@router.post("/create", response_model=ApiResponse[BookingResponse])
async def create_booking(
    booking_data: BookingCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """创建预约"""
    # 创建订单
    booking = Booking(
        id=generate_id(),
        type=booking_data.type,
        user_id=current_user.id,
        user_name=current_user.nick_name,
        venue_id=booking_data.venueId,
        venue_name=booking_data.venueName,
        venue_type=booking_data.venueType,
        latitude=booking_data.latitude,
        longitude=booking_data.longitude,
        address=booking_data.address,
        date=booking_data.date,
        start_time=booking_data.startTime,
        end_time=booking_data.endTime,
        venue_price=booking_data.venuePrice,
        service_fee=booking_data.serviceFee,
        total_price=booking_data.totalPrice,
        payment_method=booking_data.paymentMethod,
        team_id=booking_data.teamId,
        team_name=booking_data.teamName,
        match_id=booking_data.matchId,
        position=booking_data.position,
        status="pending"
    )
    
    db.add(booking)
    
    # 添加参与者（球队预约）
    if booking_data.participants:
        for participant_data in booking_data.participants:
            participant = BookingParticipant(
                id=generate_id(),
                booking_id=booking.id,
                user_id=participant_data.userId,
                user_name=participant_data.userName,
                avatar=participant_data.avatar,
                position=participant_data.position,
                confirmed=False,
                paid=False
            )
            db.add(participant)
    
    db.commit()
    db.refresh(booking)
    
    # 构造响应
    booking_dict = booking.to_dict()
    return ApiResponse(data=BookingResponse(**booking_dict))


@router.get("/detail/{booking_id}", response_model=ApiResponse[BookingResponse])
async def get_booking_detail(
    booking_id: str,
    db: Session = Depends(get_db)
):
    """获取预约详情"""
    booking = db.query(Booking).filter(Booking.id == booking_id).first()
    if not booking:
        raise HTTPException(status_code=404, detail="订单不存在")
    
    # 查询参与者
    participants = db.query(BookingParticipant).filter(
        BookingParticipant.booking_id == booking_id
    ).all()
    
    booking_dict = booking.to_dict()
    booking_dict["participants"] = [p.to_dict() for p in participants]
    
    return ApiResponse(data=BookingResponse(**booking_dict))


@router.get("/my-bookings", response_model=ApiResponse[PageData[BookingResponse]])
async def get_my_bookings(
    status: Optional[str] = Query(None),
    type: Optional[str] = Query(None),
    page: int = Query(1, ge=1),
    pageSize: int = Query(10, ge=1, le=100),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取我的预约列表"""
    query = db.query(Booking).filter(Booking.user_id == current_user.id)
    
    if status:
        query = query.filter(Booking.status == status)
    if type:
        query = query.filter(Booking.type == type)
    
    query = query.order_by(Booking.created_at.desc())
    
    total = query.count()
    bookings = query.offset((page - 1) * pageSize).limit(pageSize).all()
    
    # 构造响应
    booking_list = []
    for booking in bookings:
        booking_dict = booking.to_dict()
        booking_list.append(BookingResponse(**booking_dict))
    
    return ApiResponse(
        data=PageData(
            list=booking_list,
            total=total,
            page=page,
            pageSize=pageSize,
            hasMore=total > page * pageSize
        )
    )


@router.post("/cancel/{booking_id}", response_model=ApiResponse[str])
async def cancel_booking(
    booking_id: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """取消预约"""
    booking = db.query(Booking).filter(Booking.id == booking_id).first()
    if not booking:
        raise HTTPException(status_code=404, detail="订单不存在")
    
    if booking.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="无权操作")
    
    if booking.status == "cancelled":
        raise HTTPException(status_code=400, detail="订单已取消")
    
    booking.status = "cancelled"
    booking.cancelled_at = datetime.now()
    db.commit()
    
    return ApiResponse(data="取消成功")


@router.post("/pay/{booking_id}", response_model=ApiResponse[str])
async def pay_booking(
    booking_id: str,
    paymentMethod: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """支付订单"""
    booking = db.query(Booking).filter(Booking.id == booking_id).first()
    if not booking:
        raise HTTPException(status_code=404, detail="订单不存在")
    
    if booking.user_id != current_user.id:
        raise HTTPException(status_code=403, detail="无权操作")
    
    # TODO: 实际支付逻辑
    booking.status = "paid"
    booking.paid_at = datetime.now()
    db.commit()
    
    return ApiResponse(data="支付成功")

